package demo.com.xml;

import android.util.Log;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.InputStream;

/**
 * Created by se1 on 16-11-17.
 */
public class PullXmlParser {

    private static final String TAG = PullXmlParser.class.getSimpleName();

    public void parse(InputStream is) {
        try {
            XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
            parser.setInput(is, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        Log.w(TAG, "----解析开始----");
                        break;
                    case XmlPullParser.START_TAG:
                        Log.w(TAG, "startElement：" + parser.getName());
                        int length = parser.getAttributeCount();
                        for (int i = 0; i < length; i++) {
                            Log.d(TAG, StringUtil.padLeft("属性：" + parser.getAttributeName(i), 16, ' ') + "    值: " + parser.getAttributeValue(i));
                        }
                        break;
                    case XmlPullParser.TEXT:
                        if (0 != parser.getText().trim().length()) {
                            Log.i(TAG, "节点内容：" + parser.getText().trim());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        Log.e(TAG, "endElement：  " + parser.getName());
                        break;
                    default:
                        break;
                }
                eventType = parser.next();
            }
            Log.e(TAG, "----解析结束----");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
